# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import AccessError


class PermissionMixin(models.AbstractModel):
    """权限控制混合类 - 模仿若依数据权限"""
    _name = 'device.permission.mixin'
    _description = '设备数据权限混合类'
    
    def _get_data_scope_domain(self, domain=None):
        """
        获取数据权限域
        根据用户角色的数据权限范围返回相应的domain
        """
        if domain is None:
            domain = []
        
        # 获取当前用户
        current_user = self.env.user
        if not current_user:
            return domain
        
        # 超级管理员拥有所有数据权限
        if current_user.has_group('base.group_system'):
            return domain
        
        # 获取 device.user 记录
        device_user = self.env['device.user'].search([
            ('username', '=', current_user.login)
        ], limit=1)
        
        if not device_user:
            # 如果不是 device 用户，只能看到自己创建的记录
            domain = domain + [('create_by', '=', current_user.name)]
            return domain
        
        # 如果是超级管理员
        if device_user.is_admin:
            return domain
        
        # 获取用户的数据权限范围
        data_scope = device_user.get_user_data_scope()
        
        if data_scope == 'all':
            # 全部数据权限
            return domain
        elif data_scope == 'custom':
            # 自定数据权限 - 根据角色配置的部门
            dept_ids = device_user.get_data_scope_department_ids()
            if hasattr(self, 'department_id'):
                domain = domain + [('department_id', 'in', dept_ids)]
            return domain
        elif data_scope == 'dept':
            # 部门数据权限
            if device_user.department_id:
                if hasattr(self, 'department_id'):
                    domain = domain + [('department_id', '=', device_user.department_id.id)]
            return domain
        elif data_scope == 'dept_and_child':
            # 部门及以下数据权限
            dept_ids = device_user.get_data_scope_department_ids()
            if hasattr(self, 'department_id'):
                domain = domain + [('department_id', 'in', dept_ids)]
            return domain
        else:
            # 仅本人数据权限
            if hasattr(self, 'user_id'):
                domain = domain + [('user_id', '=', device_user.id)]
            elif hasattr(self, 'create_by'):
                domain = domain + [('create_by', '=', current_user.name)]
            return domain
    
    def _apply_equipment_permission(self, domain=None):
        """
        应用设备权限控制
        部门负责人可看到该部门下全部设备，非负责人只能看到自己绑定的设备
        """
        if domain is None:
            domain = []
        
        current_user = self.env.user
        if not current_user:
            return domain
        
        # 超级管理员拥有所有权限
        if current_user.has_group('base.group_system'):
            return domain
        
        # 获取 device.user 记录
        device_user = self.env['device.user'].search([
            ('username', '=', current_user.login)
        ], limit=1)
        
        if not device_user:
            # 非 device 用户，无权限
            return domain + [('id', '=', False)]
        
        # 如果是超级管理员
        if device_user.is_admin:
            return domain
        
        # 检查是否为部门负责人
        is_dept_leader = False
        if device_user.department_id:
            # 检查是否为当前部门或任何子部门的负责人
            all_depts = device_user.department_id.get_children_departments() + device_user.department_id
            for dept in all_depts:
                if dept.leader_id and dept.leader_id.id == current_user.id:
                    is_dept_leader = True
                    break
        
        if is_dept_leader:
            # 部门负责人：可以看到该部门及子部门下的所有设备
            dept_ids = device_user.department_id.get_children_departments().ids + [device_user.department_id.id]
            if hasattr(self, 'department_id'):
                domain = domain + [('department_id', 'in', dept_ids)]
            elif hasattr(self, 'equipment_id'):
                # 对于关联设备的模型，通过设备的部门来过滤
                equipment_ids = self.env['device.equipment'].search([('department_id', 'in', dept_ids)]).ids
                domain = domain + [('equipment_id', 'in', equipment_ids)]
        else:
            # 非部门负责人：只能看到自己绑定的设备
            if hasattr(self, 'user_id'):
                domain = domain + [('user_id', '=', device_user.id)]
            elif hasattr(self, 'equipment_id'):
                # 对于关联设备的模型，只能看到自己使用的设备
                equipment_ids = self.env['device.equipment'].search([('user_id', '=', device_user.id)]).ids
                domain = domain + [('equipment_id', 'in', equipment_ids)]
            elif hasattr(self, 'department_id'):
                # 如果没有设备使用人字段，则按部门过滤（仅本部门）
                domain = domain + [('department_id', '=', device_user.department_id.id if device_user.department_id else False)]
        
        return domain
    
    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        """重写search方法，应用数据权限"""
        # 应用设备权限控制
        args = self._apply_equipment_permission(args)
        if count:
            # 如果需要计数，调用search_count方法
            return super().search_count(args)
        else:
            # 正常搜索，不传递count参数
            return super().search(args, offset=offset, limit=limit, order=order)
    
    @api.model
    def search_count(self, args):
        """重写search_count方法，应用数据权限"""
        # 应用设备权限控制
        args = self._apply_equipment_permission(args)
        return super().search_count(args)
    
    def check_access_rights(self, operation, raise_exception=True):
        """检查访问权限"""
        try:
            return super().check_access_rights(operation, raise_exception=raise_exception)
        except AccessError:
            if raise_exception:
                raise
            return False
    
    def check_access_rule(self, operation):
        """检查访问规则"""
        # 应用数据权限检查
        if operation in ('read', 'write', 'create', 'unlink'):
            # 这里可以添加更细粒度的权限检查
            pass
        return super().check_access_rule(operation)

